{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-10-26T20:13:25.215884Z",
     "start_time": "2025-10-26T20:13:25.199789Z"
    }
   },
   "source": [
    "from agentscope.pipeline import MsgHub\n",
    "from agentscope.agent import ReActAgent, UserAgent, AgentBase\n",
    "from agentscope.formatter import DashScopeChatFormatter, DashScopeMultiAgentFormatter\n",
    "from agentscope.memory import InMemoryMemory\n",
    "from agentscope.message import Msg\n",
    "from agentscope.model import DashScopeChatModel\n",
    "from agentscope.tool import Toolkit, execute_python_code\n",
    "\n",
    "import asyncio\n",
    "import json\n",
    "import os\n",
    "\n",
    "\n"
   ],
   "outputs": [],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-26T19:44:29.141411Z",
     "start_time": "2025-10-26T19:44:23.068289Z"
    }
   },
   "cell_type": "code",
   "source": [
    "async def creating_react_agent() -> None:\n",
    "    \"\"\"创建一个 ReAct 智能体并运行一个简单任务。\"\"\"\n",
    "    # 准备工具\n",
    "    toolkit = Toolkit()\n",
    "    toolkit.register_tool_function(execute_python_code)\n",
    "\n",
    "    jarvis = ReActAgent(\n",
    "        name=\"Jarvis\",\n",
    "        sys_prompt=\"你是一个名为 Jarvis 的助手\",\n",
    "        model=DashScopeChatModel(\n",
    "            model_name=\"qwen-max\",\n",
    "            api_key=os.environ[\"AI_DASHSCOPE_API_KEY\"],\n",
    "            stream=True,\n",
    "            enable_thinking=False,\n",
    "        ),\n",
    "        formatter=DashScopeChatFormatter(),\n",
    "        toolkit=toolkit,\n",
    "        memory=InMemoryMemory(),\n",
    "    )\n",
    "\n",
    "    msg = Msg(\n",
    "        name=\"user\",\n",
    "        content=\"你好！Jarvis，用 Python 运行 Hello World。\",\n",
    "        role=\"user\",\n",
    "    )\n",
    "\n",
    "    await jarvis(msg)\n",
    "\n",
    "\n",
    "# asyncio.run(creating_react_agent())\n",
    "await creating_react_agent()"
   ],
   "id": "dde7d473abab57ba",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Jarvis: {\n",
      "    \"type\": \"tool_use\",\n",
      "    \"id\": \"call_779577de26b14f3e867218\",\n",
      "    \"name\": \"execute_python_code\",\n",
      "    \"input\": {\n",
      "        \"code\": \"print('Hello World')\",\n",
      "        \"timeout\": 300\n",
      "    }\n",
      "}\n",
      "system: {\n",
      "    \"type\": \"tool_result\",\n",
      "    \"id\": \"call_779577de26b14f3e867218\",\n",
      "    \"name\": \"execute_python_code\",\n",
      "    \"output\": [\n",
      "        {\n",
      "            \"type\": \"text\",\n",
      "            \"text\": \"Error: \"\n",
      "        }\n",
      "    ]\n",
      "}\n",
      "Jarvis: 看来在尝试执行代码时遇到了一些问题。不过，根据您的请求，这段 Python 代码`print('Hello World')`应该会输出：\n",
      "\n",
      "```\n",
      "Hello World\n",
      "```\n",
      "\n",
      "如果需要，我们可以再试一次运行代码，或者尝试其他 Python 代码段。请告诉我您下一步想要怎么做。\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-26T20:04:02.440149Z",
     "start_time": "2025-10-26T20:04:00.981961Z"
    }
   },
   "cell_type": "code",
   "source": [
    "class CustomAgent(AgentBase):\n",
    "    \"\"\"自定义智能体类\"\"\"\n",
    "\n",
    "    def __init__(self) -> None:\n",
    "        \"\"\"初始化智能体\"\"\"\n",
    "        super().__init__()\n",
    "\n",
    "        self.name = \"Friday\"\n",
    "        self.sys_prompt = \"你是一个名为 Friday 的助手。\"\n",
    "        self.model = DashScopeChatModel(\n",
    "            model_name=\"qwen-max\",\n",
    "            api_key=os.environ[\"AI_DASHSCOPE_API_KEY\"],\n",
    "            stream=False,\n",
    "        )\n",
    "        self.formatter = DashScopeChatFormatter()\n",
    "        self.memory = InMemoryMemory()\n",
    "\n",
    "    async def reply(self, msg: Msg | list[Msg] | None, *args, **kwargs) -> Msg:\n",
    "        \"\"\"直接调用大模型，产生回复消息。\"\"\"\n",
    "        await self.memory.add(msg)\n",
    "\n",
    "        # 准备提示\n",
    "        prompt = await self.formatter.format(\n",
    "            [\n",
    "                Msg(\"system\", self.sys_prompt, \"system\"),\n",
    "                *await self.memory.get_memory(),\n",
    "            ],\n",
    "        )\n",
    "\n",
    "        # 调用模型\n",
    "        response = await self.model(prompt)\n",
    "\n",
    "        msg = Msg(\n",
    "            name=self.name,\n",
    "            content=response.content,\n",
    "            role=\"assistant\",\n",
    "        )\n",
    "\n",
    "        # 在记忆中记录响应\n",
    "        await self.memory.add(msg)\n",
    "\n",
    "        # 打印消息\n",
    "        await self.print(msg)\n",
    "        return msg\n",
    "\n",
    "    async def observe(self, msg: Msg | list[Msg] | None) -> None:\n",
    "        \"\"\"观察消息。\"\"\"\n",
    "        # 将消息存储在记忆中\n",
    "        await self.memory.add(msg)\n",
    "\n",
    "    async def handle_interrupt(self) -> Msg:\n",
    "        \"\"\"处理中断。\"\"\"\n",
    "        # 以固定响应为例\n",
    "        return Msg(\n",
    "            name=self.name,\n",
    "            content=\"我注意到您打断了我的回复，我能为你做些什么？\",\n",
    "            role=\"assistant\",\n",
    "        )\n",
    "\n",
    "\n",
    "async def run_custom_agent() -> None:\n",
    "    \"\"\"运行自定义智能体。\"\"\"\n",
    "    agent = CustomAgent()\n",
    "    msg = Msg(\n",
    "        name=\"user\",\n",
    "        content=\"你是谁？\",\n",
    "        role=\"user\",\n",
    "    )\n",
    "    await agent(msg)\n",
    "\n",
    "\n",
    "# asyncio.run(run_custom_agent())\n",
    "await run_custom_agent()"
   ],
   "id": "dc4b4642ed689c1",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Friday: 我是Friday，一个设计来帮助你解答问题、提供信息和完成各种任务的助手。有什么我可以帮你的吗？\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "a97625429fcd3943"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-26T20:10:05.686290Z",
     "start_time": "2025-10-26T20:07:30.431666Z"
    }
   },
   "cell_type": "code",
   "source": [
    "friday = ReActAgent(\n",
    "    name=\"Friday\",\n",
    "    sys_prompt=\"你是一个名为 Friday 的有用助手\",\n",
    "    model=DashScopeChatModel(\n",
    "        model_name=\"qwen-max\",\n",
    "        api_key=os.environ[\"AI_DASHSCOPE_API_KEY\"],\n",
    "    ),\n",
    "    formatter=DashScopeChatFormatter(),  # 用于 user-assistant 对话的格式化器\n",
    "    memory=InMemoryMemory(),\n",
    "    toolkit=Toolkit(),\n",
    ")\n",
    "\n",
    "# 创建用户智能体\n",
    "user = UserAgent(name=\"User\")\n",
    "\n",
    "async def run_conversation() -> None:\n",
    "    \"\"\"运行 Friday 和用户之间的简单对话。\"\"\"\n",
    "    msg = None\n",
    "    while True:\n",
    "        msg = await friday(msg)\n",
    "        msg = await user(msg)\n",
    "        if msg.get_text_content() == \"exit\":\n",
    "            break\n",
    "\n",
    "# asyncio.run(run_conversation())\n",
    "await run_conversation()\n"
   ],
   "id": "e8d94bc5d3734d80",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Friday: 您好！有什么我可以帮您的吗？\n",
      "User: 刚来深圳，介绍一下深圳的特色\n",
      "Friday: 深圳是一座充满活力和创新精神的现代化大都市，位于中国广东省南部，紧邻香港。这座城市以其快速的城市发展、高科技产业以及包容多元的文化而闻名。下面是一些深圳的特色简介：\n",
      "\n",
      "1. **科技创新**：深圳被誉为中国硅谷，拥有众多国内外知名的科技公司总部或研发中心，如华为、腾讯等。这里也是创业者的天堂，吸引了大量初创企业。\n",
      "\n",
      "2. **开放包容的文化氛围**：作为一个移民城市，深圳汇聚了来自全国各地乃至世界各地的人才与文化，形成了独特而丰富的社会风貌。\n",
      "\n",
      "3. **美丽的自然风光与城市景观**：\n",
      "   - **东部华侨城**：集自然风光、休闲度假于一体的大规模旅游区。\n",
      "   - **深圳湾公园**：沿着海岸线延伸，是市民休闲散步的好去处。\n",
      "   - **莲花山公园**：可以俯瞰整个深圳市区美景的地方之一。\n",
      "   \n",
      "4. **购物天堂**：从高端奢华品牌到平价商品应有尽有，尤其是华强北电子市场，在这里几乎可以买到任何类型的电子产品。\n",
      "\n",
      "5. **美食多样**：由于人口构成复杂，深圳汇集了全国各地乃至海外的各种风味小吃及正餐，无论您想尝试哪种口味都能在这里找到满意的选择。\n",
      "\n",
      "6. **便捷交通网络**：深圳拥有发达的公共交通系统，包括地铁、公交等，方便快捷地连接着城市的各个角落。同时，作为国际航空枢纽之一，深圳宝安国际机场也提供了通往世界各地的航班服务。\n",
      "\n",
      "7. **丰富多样的节庆活动**：每年都会举办各种文化节、艺术展等活动，为市民和游客提供了一个了解当地文化及享受娱乐生活的平台。\n",
      "\n",
      "总之，深圳不仅是一个经济高度发展的城市，同时也是一座非常适合居住、工作和旅行的目的地。希望这些信息能帮助你更好地了解这座魅力之城！如果有更具体的需求或者其他问题，请随时告诉我哦～\n",
      "User: 介绍一下深圳各个区的特色\n",
      "Friday: 深圳下辖10个行政区和一个新区，每个区都有其独特的特色和发展重点。下面我将为您简要介绍各个区的特点：\n",
      "\n",
      "1. **福田区**：作为深圳市的政治、文化和商业中心，福田区内有多个重要的政府机构及文化设施（如市民中心），同时还是金融服务业的重要聚集地之一。\n",
      "\n",
      "2. **罗湖区**：历史悠久的老城区，以东门步行街为代表的商业街区非常有名；也是珠宝首饰产业的重镇。\n",
      "\n",
      "3. **南山区**：被誉为“中国硅谷”，是高科技企业和创新孵化器的主要集中地，拥有众多知名高校与科研机构，并且靠近海岸线，自然风光优美。\n",
      "\n",
      "4. **宝安区**：制造业基础雄厚，特别是电子信息技术领域；宝安国际机场位于此区，使得该区域成为了重要的物流交通枢纽。\n",
      "\n",
      "5. **龙岗区**：近年来发展迅速的新城区，以大运新城为代表的城市建设日新月异；同时保留了丰富的客家文化遗产。\n",
      "\n",
      "6. **盐田区**：以港口经济为主导，盐田港是世界第四大集装箱港；此外还拥有美丽的海滨风光，如大梅沙海滩等旅游景点。\n",
      "\n",
      "7. **光明新区**：专注于高新技术产业发展，特别是在生物医药、新能源新材料等方面具有明显优势。\n",
      "\n",
      "8. **坪山区**：新兴的工业基地，重点发展电子信息、生物医药等战略性新兴产业；生态环境良好，有马峦山郊野公园等自然景观。\n",
      "\n",
      "9. **龙华区**：以富士康等大型企业为代表，形成了较为完整的产业链条；同时也在积极推进城市更新改造项目。\n",
      "\n",
      "10. **大鹏新区**：以生态旅游著称，拥有较场尾、杨梅坑等多个著名旅游景区；致力于打造成为世界级滨海生态旅游度假区。\n",
      "\n",
      "11. **深汕特别合作区**：这是深圳与汕尾市共同开发的一个特殊区域，旨在探索跨区域合作新模式，在推动两地经济社会协调发展方面发挥着重要作用。\n",
      "\n",
      "以上就是对深圳各区基本情况的大致概述，不同区域根据自身条件与发展定位呈现出多样化的发展格局。希望这些信息对你有所帮助！如果需要更详细的信息或其他方面的指导，请随时向我询问。\n",
      "Friday: 深圳下辖10个行政区和一个新区，每个区都有其独特的特色和发展重点。下面我将为您简要介绍各个区的特点：\n",
      "\n",
      "1. **福田区**：作为深圳市的政治、文化和商业中心，福田区内有多个重要的政府机构及文化设施（如市民中心），同时还是金融服务业的重要聚集地之一。\n",
      "\n",
      "2. **罗湖区**：历史悠久的老城区，以东门步行街为代表的商业街区非常有名；也是珠宝首饰产业的重镇。\\\n",
      "3. **南山区**：被誉为“中国硅谷”，是高科技企业和创新孵化器的主要集中地，拥有众多知名高校与科研机构，并且靠近海岸线，自然风光优美。\\\n",
      "4. **宝安区**：制造业基础雄厚，特别是电子信息技术领域；宝安国际机场位于此区，使得该区域成为了重要的物流交通枢纽。\n",
      "\n",
      "5. **龙岗区**：近年来发展迅速的新城区，以大运新城为代表的城市建设日新月异；同时保留了丰富的客家文化遗产。\n",
      "\n",
      "6. **盐田区**：以港口经济为主导，盐田港是世界第四大集装箱港；此外还拥有美丽的海滨风光，如大梅沙海滩等旅游景点。\n",
      "\n",
      "7. **光明新区**：专注于高新技术产业发展，特别是在生物医药、新能源新材料等方面具有明显优势。\n",
      "\n",
      "8. **坪山区**：新兴的工业基地，重点发展电子信息、生物医药等战略性新兴产业；生态环境良好，有马峦山郊野公园等自然景观。\\\n",
      "9. **龙华区**：以富士康等大型企业为代表，形成了较为完整的产业链条；同时也在积极推进城市更新改造项目。\n",
      "\n",
      "10. **大鹏新区**：以生态旅游著称，拥有较场尾、杨梅坑等多个著名旅游景区；致力于打造成为世界级滨海生态旅游度假区。\n",
      "\n",
      "11. **深汕特别合作区**：这是深圳与汕尾市共同开发的一个特殊区域，旨在探索跨区域合作新模式，在推动两地经济社会协调发展方面发挥着重要作用。\n",
      "\n",
      "以上就是对深圳各区基本情况的大致概述，不同区域根据自身条件与发展定位呈现出多样化的发展格局。希望这些信息对你有所帮助！如果需要更详细的信息或其他方面的指导，请随时向我询问。\n",
      "User: exit()\n",
      "Friday: 好的，如果您有任何其他问题或需要进一步的帮助，请随时告诉我。祝您在深圳生活愉快！再见！\n",
      "User: exit\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "async def example_multi_agent_prompt() -> None:\n",
    "    msgs = [\n",
    "        Msg(\"system\", \"你是一个名为 Bob 的有用助手。\", \"system\"),\n",
    "        Msg(\"Alice\", \"嗨！\", \"user\"),\n",
    "        Msg(\"Bob\", \"嗨！很高兴见到大家。\", \"assistant\"),\n",
    "        Msg(\"Charlie\", \"我也是！顺便说一下，我是 Charlie。\", \"assistant\"),\n",
    "    ]\n",
    "\n",
    "    formatter = DashScopeMultiAgentFormatter()\n",
    "    prompt = await formatter.format(msgs)\n",
    "\n",
    "    print(\"格式化的提示：\")\n",
    "    print(json.dumps(prompt, indent=4, ensure_ascii=False))\n",
    "\n",
    "    # 我们在这里打印组合用户消息的内容以便更好地理解：\n",
    "    print(\"-------------\")\n",
    "    print(\"组合消息\")\n",
    "    print(prompt[1][\"content\"])\n",
    "\n",
    "\n",
    "# asyncio.run(example_multi_agent_prompt())\n",
    "await example_multi_agent_prompt()"
   ],
   "id": "3f49ad24ccb1a18a"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "model = DashScopeChatModel(\n",
    "    model_name=\"qwen-max\",\n",
    "    api_key=os.environ[\"AI_DASHSCOPE_API_KEY\"],\n",
    ")\n",
    "formatter = DashScopeMultiAgentFormatter()\n",
    "\n",
    "alice = ReActAgent(\n",
    "    name=\"Alice\",\n",
    "    sys_prompt=\"你是一个名为 Alice 的学生。\",\n",
    "    model=model,\n",
    "    formatter=formatter,\n",
    ")\n",
    "\n",
    "bob = ReActAgent(\n",
    "    name=\"Bob\",\n",
    "    sys_prompt=\"你是一个名为 Bob 的学生。\",\n",
    "    model=model,\n",
    "    formatter=formatter,\n",
    ")\n",
    "\n",
    "charlie = ReActAgent(\n",
    "    name=\"Charlie\",\n",
    "    sys_prompt=\"你是一个名为 Charlie 的学生。\",\n",
    "    model=model,\n",
    "    formatter=formatter,\n",
    ")\n",
    "\n",
    "\n",
    "async def example_msghub() -> None:\n",
    "    \"\"\"使用 MsgHub 进行多智能体对话的示例。\"\"\"\n",
    "    async with MsgHub(\n",
    "        [alice, bob, charlie],\n",
    "        # 进入 MsgHub 时的公告消息\n",
    "        announcement=Msg(\n",
    "            \"system\",\n",
    "            \"现在大家互相认识一下，简单自我介绍。\",\n",
    "            \"system\",\n",
    "        ),\n",
    "    ):\n",
    "        await alice()\n",
    "        await bob()\n",
    "        await charlie()\n",
    "\n",
    "\n",
    "asyncio.run(example_msghub())"
   ],
   "id": "ae1f1704b9b85f8"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import asyncio\n",
    "import json\n",
    "import os\n",
    "from typing import Literal\n",
    "\n",
    "from pydantic import BaseModel, Field\n",
    "\n",
    "from agentscope.agent import ReActAgent\n",
    "from agentscope.formatter import DashScopeChatFormatter\n",
    "from agentscope.memory import InMemoryMemory\n",
    "from agentscope.message import Msg\n",
    "from agentscope.model import DashScopeChatModel\n",
    "from agentscope.tool import Toolkit, ToolResponse\n",
    "\n",
    "router = ReActAgent(\n",
    "    name=\"Router\",\n",
    "    sys_prompt=\"你是一个路由智能体。你的目标是将用户查询路由到正确的后续任务，注意你不需要回答用户的问题。\",\n",
    "    model=DashScopeChatModel(\n",
    "        model_name=\"qwen-max\",\n",
    "        api_key=os.environ[\"AI_DASHSCOPE_API_KEY\"],\n",
    "        stream=False,\n",
    "    ),\n",
    "    formatter=DashScopeChatFormatter(),\n",
    ")\n",
    "\n",
    "\n",
    "# 使用结构化输出指定路由任务\n",
    "class RoutingChoice(BaseModel):\n",
    "    your_choice: Literal[\n",
    "        \"Content Generation\",\n",
    "        \"Programming\",\n",
    "        \"Information Retrieval\",\n",
    "        None,\n",
    "    ] = Field(\n",
    "        description=\"选择正确的后续任务，如果任务太简单或没有合适的任务，则选择 ``None``\",\n",
    "    )\n",
    "    task_description: str | None = Field(\n",
    "        description=\"任务描述\",\n",
    "        default=None,\n",
    "    )\n",
    "\n",
    "\n",
    "async def example_router_explicit() -> None:\n",
    "    \"\"\"使用结构化输出进行显式路由的示例。\"\"\"\n",
    "    msg_user = Msg(\n",
    "        \"user\",\n",
    "        \"帮我写一首诗\",\n",
    "        \"user\",\n",
    "    )\n",
    "\n",
    "    # 路由查询\n",
    "    msg_res = await router(\n",
    "        msg_user,\n",
    "        structured_model=RoutingChoice,\n",
    "    )\n",
    "\n",
    "    # 结构化输出存储在 metadata 字段中\n",
    "    print(\"结构化输出：\")\n",
    "    print(json.dumps(msg_res.metadata, indent=4, ensure_ascii=False))\n",
    "\n",
    "\n",
    "asyncio.run(example_router_explicit())"
   ],
   "id": "c654408217d3bf42"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "async def generate_python(demand: str) -> ToolResponse:\n",
    "    \"\"\"根据需求生成 Python 代码。\n",
    "\n",
    "    Args:\n",
    "        demand (``str``):\n",
    "            对 Python 代码的需求。\n",
    "    \"\"\"\n",
    "    # 示例需求智能体\n",
    "    python_agent = ReActAgent(\n",
    "        name=\"PythonAgent\",\n",
    "        sys_prompt=\"你是一个 Python 专家，你的目标是根据需求生成 Python 代码。\",\n",
    "        model=DashScopeChatModel(\n",
    "            model_name=\"qwen-max\",\n",
    "            api_key=os.environ[\"AI_DASHSCOPE_API_KEY\"],\n",
    "            stream=False,\n",
    "        ),\n",
    "        memory=InMemoryMemory(),\n",
    "        formatter=DashScopeChatFormatter(),\n",
    "        toolkit=Toolkit(),\n",
    "    )\n",
    "    msg_res = await python_agent(Msg(\"user\", demand, \"user\"))\n",
    "\n",
    "    return ToolResponse(\n",
    "        content=msg_res.get_content_blocks(\"text\"),\n",
    "    )\n",
    "\n",
    "\n",
    "# 为演示目的模拟一些其他工具函数\n",
    "async def generate_poem(demand: str) -> ToolResponse:\n",
    "    \"\"\"根据需求生成诗歌。\n",
    "\n",
    "    Args:\n",
    "        demand (``str``):\n",
    "            对诗歌的需求。\n",
    "    \"\"\"\n",
    "    pass\n",
    "\n",
    "\n",
    "async def web_search(query: str) -> ToolResponse:\n",
    "    \"\"\"在网络上搜索查询。\n",
    "\n",
    "    Args:\n",
    "        query (``str``):\n",
    "            要搜索的查询。\n",
    "    \"\"\"\n",
    "    pass\n",
    "\n",
    "\n",
    "\n",
    "# 使用工具模块初始化路由智能体\n",
    "router_implicit = ReActAgent(\n",
    "    name=\"Router\",\n",
    "    sys_prompt=\"你是一个路由智能体。你的目标是将用户查询路由到正确的后续任务。\",\n",
    "    model=DashScopeChatModel(\n",
    "        model_name=\"qwen-max\",\n",
    "        api_key=os.environ[\"AI_DASHSCOPE_API_KEY\"],\n",
    "        stream=False,\n",
    "    ),\n",
    "    formatter=DashScopeChatFormatter(),\n",
    "    toolkit=Toolkit(),\n",
    "    memory=InMemoryMemory(),\n",
    ")\n",
    "\n",
    "\n",
    "async def example_router_implicit() -> None:\n",
    "    \"\"\"使用工具调用进行隐式路由的示例。\"\"\"\n",
    "    msg_user = Msg(\n",
    "        \"user\",\n",
    "        \"帮我在 Python 中生成一个快速排序函数\",\n",
    "        \"user\",\n",
    "    )\n",
    "\n",
    "    # 路由查询\n",
    "    await router_implicit(msg_user)\n",
    "\n",
    "\n",
    "# asyncio.run(example_router_implicit())\n",
    "await example_router_implicit()"
   ],
   "id": "e5f8aa487dd47b47"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import asyncio\n",
    "import os\n",
    "\n",
    "from agentscope.agent import ReActAgent\n",
    "from agentscope.formatter import DashScopeChatFormatter\n",
    "from agentscope.memory import InMemoryMemory\n",
    "from agentscope.message import Msg\n",
    "from agentscope.model import DashScopeChatModel\n",
    "from agentscope.tool import (\n",
    "    ToolResponse,\n",
    "    Toolkit,\n",
    "    execute_python_code,\n",
    ")\n",
    "\n",
    "\n",
    "# 创建子智能体的工具函数\n",
    "async def create_worker(\n",
    "    task_description: str,\n",
    ") -> ToolResponse:\n",
    "    \"\"\"创建一个子智能体来完成给定的任务。子智能体配备了 Python 执行工具。\n",
    "\n",
    "    Args:\n",
    "        task_description (``str``):\n",
    "            子智能体要完成的任务描述。\n",
    "    \"\"\"\n",
    "    # 为子智能体智能体配备一些工具\n",
    "    toolkit = Toolkit()\n",
    "    toolkit.register_tool_function(execute_python_code)\n",
    "\n",
    "    # 创建子智能体智能体\n",
    "    worker = ReActAgent(\n",
    "        name=\"Worker\",\n",
    "        sys_prompt=\"你是一个智能体。你的目标是完成给定的任务。\",\n",
    "        model=DashScopeChatModel(\n",
    "            model_name=\"qwen-max\",\n",
    "            api_key=os.environ[\"AI_DASHSCOPE_API_KEY\"],\n",
    "            stream=False,\n",
    "        ),\n",
    "        formatter=DashScopeChatFormatter(),\n",
    "        toolkit=toolkit,\n",
    "    )\n",
    "    # 让子智能体完成任务\n",
    "    res = await worker(Msg(\"user\", task_description, \"user\"))\n",
    "    return ToolResponse(\n",
    "        content=res.get_content_blocks(\"text\"),\n",
    "    )\n",
    "\n",
    "\n",
    "async def run_handoffs() -> None:\n",
    "    \"\"\"交接工作流示例。\"\"\"\n",
    "    # 初始化协调者智能体\n",
    "    toolkit = Toolkit()\n",
    "    toolkit.register_tool_function(create_worker)\n",
    "\n",
    "    orchestrator = ReActAgent(\n",
    "        name=\"Orchestrator\",\n",
    "        sys_prompt=\"你是一个协调者智能体。你的目标是通过将任务分解为更小的任务并创建子智能体来完成它们，从而完成给定的任务。\",\n",
    "        model=DashScopeChatModel(\n",
    "            model_name=\"qwen-max\",\n",
    "            api_key=os.environ[\"DASHSCOPE_API_KEY\"],\n",
    "            stream=False,\n",
    "        ),\n",
    "        memory=InMemoryMemory(),\n",
    "        formatter=DashScopeChatFormatter(),\n",
    "        toolkit=toolkit,\n",
    "    )\n",
    "\n",
    "    # 任务描述\n",
    "    task_description = \"在 Python 中执行 hello world\"\n",
    "\n",
    "    # 创建子智能体来完成任务\n",
    "    await orchestrator(Msg(\"user\", task_description, \"user\"))\n",
    "\n",
    "\n",
    "asyncio.run(run_handoffs())"
   ],
   "id": "fae4e90dc8c63bb6"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
